//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.kun.portal.webframe.service;

import com.kun.framework.web.web.vo.ValueLabelVo;
import com.kun.portal.util.QueryHelper;
import com.kun.portal.webframe.dao.FwRoleDao;
import com.kun.portal.webframe.dao.FwRoleModuleDao;
import com.kun.portal.webframe.dao.FwUserDao;
import com.kun.portal.webframe.po.FwRoleModulePo;
import com.kun.portal.webframe.po.FwRolePo;
import com.kun.portal.webframe.po.FwTeamPo;
import com.kun.portal.webframe.po.FwUserPo;
import com.kun.portal.webframe.vo.RoleTeamVo;
import com.kun.portal.webframe.vo.Teams;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class FwRoleService {
    @Autowired
    private FwRoleDao fwroleDao;
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private FwUserDao fwUserDao;
    @Autowired
    private FwRoleDao fwRoleDao;
    @Autowired
    private FwRoleModuleDao moduleDao;

    public FwRoleService() {
    }

    public Page<FwRolePo> queryAll(Pageable pageable) {
        return this.fwroleDao.findAll(pageable);
    }

    public Page<FwRolePo> queryAll(String key, Pageable pageable) {
        return StringUtils.isEmpty(key)?this.fwroleDao.findAll(pageable):this.fwroleDao.findByKey("%" + key + "%", pageable);
    }

    public Page<FwRolePo> queryByCreatorAndRoleTypeAndRoleNameContainingOrderByRoleCode(String userId, String roleType, String roleName, Pageable pageable) {
        return this.fwroleDao.queryByCreatorAndRoleTypeAndRoleNameContainingOrderByRoleCode(userId, roleType, roleName, pageable);
    }

    public Page<FwRolePo> queryRoleByTeam(String teamId, String key, Pageable pageable) {
        if(StringUtils.isNotBlank(key)) {
            key = "%" + key.trim() + "%";
            return this.fwroleDao.queryRoleByTeamAndKey(teamId, key, pageable);
        } else {
            return this.fwroleDao.queryRoleByTeam(teamId, pageable);
        }
    }

    public Page<FwRolePo> queryRoleTeam(String teamId, String key, Pageable pageable) {
        return StringUtils.isNotBlank(key)?this.fwroleDao.findByTeamIdLikeAndKey(teamId, key, pageable):this.fwroleDao.findByTeamIdLike(teamId, pageable);
    }

    public FwRolePo addFwRole(FwRolePo fwrole) {
        FwRolePo fwrolePo = (FwRolePo)this.fwroleDao.save(fwrole);
        String roleId = fwrolePo.getRoleId();
        List<String> moduleList = fwrole.getModuleList();
        if(moduleList != null) {
            this.moduleDao.deleteByRoleId(roleId);
            List<FwRoleModulePo> roleModuleList = new ArrayList();
            Iterator var7 = moduleList.iterator();

            while(var7.hasNext()) {
                String moduleId = (String)var7.next();
                roleModuleList.add(new FwRoleModulePo(roleId, moduleId));
            }

            this.moduleDao.save(roleModuleList);
        }

        return fwrolePo;
    }

    @Transactional
    public FwRolePo updateFwRole(FwRolePo fwrole) {
        FwRolePo fwrolePo = (FwRolePo)this.fwroleDao.save(fwrole);
        String roleId = fwrolePo.getRoleId();
        List<String> moduleList = fwrole.getModuleList();
        this.saveTeamModule(roleId, moduleList);
        return fwrolePo;
    }

    public void saveTeamModule(String roleId, List<String> moduleList) {
        if(moduleList != null) {
            this.moduleDao.deleteByRoleId(roleId);
            List<FwRoleModulePo> roleModuleList = new ArrayList();
            Iterator var5 = moduleList.iterator();

            while(var5.hasNext()) {
                String moduleId = (String)var5.next();
                roleModuleList.add(new FwRoleModulePo(roleId, moduleId));
            }

            this.moduleDao.save(roleModuleList);
        }

    }

    @Transactional
    public void deleteFwRole(String roleId) {
        this.fwroleDao.delete(roleId);
    }

    public List<FwRolePo> findFwRoleByCreator(String creatorId) {

        //query.setParameter(1, creatorId);
        return fwroleDao.findAll();
    }

    public List<RoleTeamVo> findFwRoleByTeam(String teamId) {
        Query query = this.entityManager.createNativeQuery("SELECT r.role_id AS VALUE, r.role_code AS CODE, r.role_name AS label ,t.team_name teamName  FROM fw_role r LEFT JOIN fw_team t ON r.team_id = t.team_id  WHERE r.role_status!='0' AND t.team_status!='0' AND r.team_id LIKE ?1 OR t.team_id IS NULL OR r.team_id = ''", RoleTeamVo.class);
        query.setParameter(1, teamId);
        return query.getResultList();
    }

    public List<RoleTeamVo> findFwRoleByTeam(FwTeamPo fwTeam) {
//        String teamId = fwTeam.getTeamId();
//        String level = fwTeam.getTeamLevel();
        Query query;
        query = this.entityManager.createNativeQuery("SELECT r.role_id AS VALUE, r.role_code AS CODE, r.role_name AS label ," +
                "t.team_name teamName   FROM fw_role r LEFT JOIN fw_team t ON r.team_id = t.team_id  " +
                "WHERE r.role_status='1' ", RoleTeamVo.class);
        return query.getResultList();
//        if(Teams.SysTeam.name().equals(teamId)) {
//            query = this.entityManager.createNativeQuery("SELECT r.role_id AS VALUE, r.role_code AS CODE, r.role_name AS label ,t.team_name teamName   FROM fw_role r LEFT JOIN fw_team t ON r.team_id = t.team_id  WHERE r.role_status='1'   and ( r.team_id is null         or t.team_status='1'        )", RoleTeamVo.class);
//            return query.getResultList();
//        } else if("1".equals(level)) {
//            query = this.entityManager.createNativeQuery("SELECT r.role_id AS VALUE, r.role_code AS CODE, r.role_name AS label ,t.team_name teamName   FROM fw_role r LEFT JOIN fw_team t ON r.team_id = t.team_id  WHERE r.role_status='1'   and ( r.team_id is null         or (t.team_status='1' and t.team_id like ?1)        )", RoleTeamVo.class);
//            query.setParameter(1, teamId);
//            return query.getResultList();
//        } else {
//            query = this.entityManager.createNativeQuery("SELECT r.role_id AS VALUE, r.role_code AS CODE, r.role_name AS label ,t.team_name teamName   FROM fw_role r JOIN fw_team t ON r.team_id = t.team_id  WHERE r.role_status='1'   and t.team_status='1'    and t.team_id like ?1 ", RoleTeamVo.class);
//            query.setParameter(1, teamId);
//            return query.getResultList();
//        }
    }

    public List<String> findFwRoleByUserId(String userId) {
        Query query = this.entityManager.createNativeQuery("select r.role_id from fw_role_user r where r.user_id=?1");
        query.setParameter(1, userId);
        return query.getResultList();
    }

    public List findFwRoleByUserIdAndTeamId(String userId, String teamId) {
        Query query = this.entityManager.createNativeQuery("SELECT a.role_id, a.role_code, c.user_id, c.team_id,d.team_name,d.team_level FROM fw_role a, fw_role_user b, fw_team_user c,fw_team d  WHERE a.role_id = b.role_id AND b.user_id = c.user_id and c.team_id = d.team_id  AND a.role_status!='0' AND d.team_status!='0'  AND c.user_id = ?1 AND c.team_id = ?2 and d.team_level='1'");
        query.setParameter(1, userId);
        query.setParameter(2, teamId);
        ((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    public List<String> findFwRoleByModuleId(String moduleId) {
        Query query = this.entityManager.createNativeQuery("select r.role_id from fw_role_module r where r.module_id=?1");
        query.setParameter(1, moduleId);
        return query.getResultList();
    }

    public List<String> findFwRoleByTeamId(String teamId) {
        Query query = this.entityManager.createNativeQuery("select r.role_id from fw_team_role r where r.team_id=?1");

        query.setParameter(1, teamId);
        return query.getResultList();
    }

    @Transactional
    public void updateFwRoleUserByUserId(List<String> roleIds, String userId) {
        FwUserPo user = (FwUserPo)this.fwUserDao.findOne(userId);
        Set<FwRolePo> roleSet = new HashSet();
        Iterator var6 = roleIds.iterator();

        while(var6.hasNext()) {
            String roleId = (String)var6.next();
            FwRolePo role = new FwRolePo();
            role.setRoleId(roleId);
            roleSet.add(role);
        }

        user.setRoles(roleSet);
        this.fwUserDao.save(user);
    }

    @Transactional
    public void updateFwRoleTeamByRoleId(List<String> teamIds, String roleId) {
    }

    @Transactional
    public Set<FwTeamPo> findTeamsByRoleId(String roleId) {
        FwRolePo resultRole = (FwRolePo)this.fwroleDao.findOne(roleId);
        Set<FwTeamPo> set = new HashSet();
        //set.add(resultRole.getTeamPo());
        return set;
    }

    @Transactional
    public void updateFwRoleUserByRoleId(String roleId, List<FwUserPo> userList) {
        FwRolePo rolePo = (FwRolePo)this.fwroleDao.findOne(roleId);
        Hibernate.initialize(rolePo.getUserList());
        rolePo.getUserList().clear();
        this.entityManager.merge(rolePo);
        rolePo.setUserList(userList);
        this.fwroleDao.save(rolePo);
    }

    public Page<FwRolePo> findRoleByTeamIdLike(String teamId, Pageable pageable) {
        return this.fwroleDao.findByTeamIdContaining(teamId, pageable);
    }

    public Page<FwRolePo> findRoleByTeamIdLikeAndKeyLike(String teamId, String key, Pageable pageable) {
        return StringUtils.isEmpty(key)?this.fwroleDao.findByTeamIdContaining(teamId, pageable):this.fwroleDao.findByTeamIdLikeAndKeyLike(teamId + "%", "%" + key + "%", pageable);
    }

    public Map countFwRole(String roleId) {
        Query query = this.entityManager.createNativeQuery("SELECT (SELECT COUNT(*) FROM fw_role_user WHERE role_id=?1) userNum, (SELECT COUNT(*) FROM fw_role_module WHERE role_id=?1) moduleNum FROM fw_role WHERE role_status!='0' AND role_id=?1");
        query.setParameter(1, roleId);
        ((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        Map map = (Map)query.getResultList().get(0);
        Map returnMap = new HashMap();
        returnMap.put("userNum", map.get("userNum"));
        returnMap.put("moduleNum", map.get("moduleNum"));
        return returnMap;
    }

    public FwRolePo findOne(String roleId) {
        return (FwRolePo)this.fwroleDao.findOne(roleId);
    }

    @Transactional
    public void updateFwRoleUserByTeam(String teamId) {
        this.fwroleDao.updateFwRoleUserByTeam(teamId);
    }

    @Transactional
    public void deleteFwRoleUserByUserId(String userId) {
        this.fwroleDao.deleteFwRoleUserByUserId(userId);
    }

    public Page<FwRolePo> queryWithParams(FwTeamPo fwTeam, final String key, Pageable pageable) {
       // final String teamId = fwTeam.getTeamId();
        //final String level = fwTeam.getTeamLevel();
        return this.fwroleDao.findAll(new Specification<FwRolePo>() {
            public Predicate toPredicate(Root<FwRolePo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> ps = new ArrayList();
                ArrayList orPs;
                if(StringUtils.isNotBlank(key)) {
                    orPs = new ArrayList();
                    orPs.add(cb.like(root.get("roleName"), "%" + key.trim() + "%"));
                    orPs.add(cb.like(root.get("roleCode"), "%" + key.trim() + "%"));
                    ps.add(cb.or((Predicate[])orPs.toArray(new Predicate[0])));
                }
                query.where(cb.and((Predicate[])ps.toArray(new Predicate[0])));
                query.orderBy(new Order[]{cb.asc(root.get("roleCode"))});
                return query.getGroupRestriction();
            }
        }, pageable);
    }

    public List<FwRolePo> check(final Map<String, String> map) {
        return this.fwroleDao.findAll(new Specification<FwRolePo>() {
            public Predicate toPredicate(Root<FwRolePo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> ps = new ArrayList();
                if(StringUtils.isNotBlank((CharSequence)map.get("roleName"))) {
                    List<Predicate> subPs = new ArrayList();
                    subPs.add(cb.equal(root.get("roleName").as(String.class), map.get("roleName")));
                    if(StringUtils.isNotBlank((CharSequence)map.get("teamId"))) {
                        subPs.add(cb.equal(root.get("teamId").as(String.class), map.get("teamId")));
                    }

                    ps.add(cb.and((Predicate[])subPs.toArray(new Predicate[0])));
                }

                if(StringUtils.isNotBlank((CharSequence)map.get("roleCode"))) {
                    ps.add(cb.equal(root.get("roleCode").as(String.class), map.get("roleCode")));
                }

                query.where(cb.or((Predicate[])ps.toArray(new Predicate[0])));
                return query.getRestriction();
            }
        });
    }

    public Page<Map<String, Object>> findFwUserByRoleId(String roleId, Pageable pageable) {
        String sql = "select * from fw_user where user_id in (select r.user_id from fw_role_user r where r.role_id='" + roleId + "')";
        Page<Map<String, Object>> users = QueryHelper.queryWithJdbc(sql, new String[0], pageable);
        return users;
    }
}
